<template>
  <div>
    <!-- 权限点数据展示 -->
    <el-tree
      ref="refTree"
      :data="list"
      :props="{ label: 'name' }"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      node-key="id"
    />
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="hSubmit">确定</el-button>
      <el-button @click="hCancel">取消</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permission'
import { getRoleDetail, assignPrem } from '@/api/settings'
import { tranListToTreeData } from '@/utils/index'
export default {
  props: {
    roleId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: [] // 存储权限数据
    }
  },
  created() {
    this.loadPermissionList()
    // 调用接口，获取当前这个角色已经具备的权限
  },

  methods: {
    async loadPermissionByRoleId() {
    // 根据roleId获取当前这个角色已经具备的权限
      const res = await getRoleDetail(this.roleId)
      console.log('获取当前角色的已有的权限点数据', res.data.permIds)
    },
    async loadPermissionList() {
      try {
        // 发送请求, 获取权限列表
        const res = await getPermissionList()
        console.log('getPermissionList', res)
        const perIds = await getRoleDetail(this.roleId)
        console.log('getRoleDetail', perIds)
        // 回填
        this.$refs.refTree.setCheckedKeys(perIds.data.permIds)
        this.list = tranListToTreeData(res.data)
      } catch (err) {
        console.log('getRoleDetail', err)
      }
    },
    async hSubmit() {
      try {
        const permIds = this.$refs.refTree.getCheckedKeys()
        const res = await assignPrem({ id: this.roleId, permIds: permIds })
        console.log('assignPrem', res)
        // 保存数据
        this.$emit('close')
      } catch (err) {
        console.log('assignPrem', err)
      }
    },
    hCancel() {
    // 通过父组件去关闭弹层
      this.$emit('close')
      // 清空当前的选择
      this.$refs.refTree.setCheckedKeys([])
    }
  }
}
</script>

<style>

</style>
